# hooks/hook.py
import importlib
import os.path
import subprocess

import pkg_resources
from PyInstaller.utils.hooks import collect_data_files, collect_dynamic_libs, get_package_paths


def get_hidden_imports():
    # result = subprocess.run(['pip3', 'list', '--format=freeze'], stdout=subprocess.PIPE, text=True)
    # packages = [line.split('==')[0] for line in result.stdout.split('\n') if '==' in line]
    installed_packages = []
    for d in pkg_resources.working_set:
        top_level_path=d.location+'\\'+d.egg_name()[:-7]+'.dist-info\\top_level.txt'
        if os.path.exists(top_level_path):
            with open(top_level_path,'r',encoding='utf-8') as f:
                pkg_name=f.read().strip()
        else:
            pkg_name=d.project_name
        installed_packages.append(pkg_name)
    # 排除一些常见的开发工具
    excluded_packages = ['pip', 'setuptools', 'wheel']
    hiddenimports = [pkg for pkg in installed_packages if pkg not in excluded_packages]

    # 收集数据文件和二进制文件
    datas = []
    binaries = []
    for package in hiddenimports:
        package_path = get_package_paths(package)
        if package_path:
            datas.extend(collect_data_files(package))
            binaries.extend(collect_dynamic_libs(package))

    return datas, binaries, hiddenimports

datas, binaries, hiddenimports = get_hidden_imports()